package stone926.mods.more_enchantments.enchantments.negative;

import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.LivingEntity;
import net.minecraft.item.ArmorItem;
import net.minecraft.item.ItemStack;
import stone926.mods.more_enchantments.MoreEnchantmentsMod;
import stone926.mods.more_enchantments.damage.StoneEntityDamageSource;
import stone926.mods.more_enchantments.interfaces.ILivingEntity;

import java.util.Random;

import static net.minecraft.enchantment.EnchantmentTarget.ARMOR;
import static stone926.mods.more_enchantments.util.EnchantmentUtil.ALL_ARMOR;

public class MakeAmendsEnchantment extends AbstractNegativeEnchantment {

  public MakeAmendsEnchantment() {
    super(ARMOR, ALL_ARMOR);
  }

  public static boolean shouldDamageSelf(int level, Random random) {
    if (level <= 0) {
      return false;
    } else {
      return random.nextFloat() < 0.2F * (float) level;
    }
  }

  public static float getDamageAmount(int lvl, Random random) {
    if (lvl <= 0) return 0;
    return lvl + random.nextInt(lvl / 2 + 1);
  }

  public static int getArmorDamage(int lvl, Random r) {
    return r.nextInt(lvl) - 2 <= 0 ? lvl : 0;
  }

  public int getMinPower(int level) {
    return 10 + 20 * (level - 1);
  }

  public int getMaxPower(int level) {
    return super.getMinPower(level) + 50;
  }

  public int getMaxLevel() {
    return 3;
  }

  public boolean isAcceptableItem(ItemStack stack) {
    return stack.getItem() instanceof ArmorItem || super.isAcceptableItem(stack);
  }

  public void onUserDamaged(LivingEntity user, Entity attacker, int level) {
    if (attacker == null) return;

    Random random = user.getRandom();

    int lvlSum = 0;
    for (EquipmentSlot slot : slots) {
      ItemStack stack = user.getEquippedStack(slot);
      int level1 = EnchantmentHelper.getLevel(MoreEnchantmentsMod.MAKE_AMENDS, stack);
      if (level1 > 0) lvlSum += level1;
      if (lvlSum > 0 && random.nextInt(lvlSum) > 3) {
        stack.damage(getArmorDamage(lvlSum, random), user, (livingEntity) -> {
          livingEntity.sendEquipmentBreakStatus(slot);
        });
      }
    }

    ((ILivingEntity) (user)).forceDamage(StoneEntityDamageSource.makeAmends(attacker), getDamageAmount(lvlSum, random));

  }

}
